package cn.jussi.mvcproject.controller;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.jussi.mvcproject.model.Online;
import cn.jussi.mvcproject.model.User;
import cn.jussi.mvcproject.service.FactoryService;
import cn.jussi.mvcproject.service.OnlineService;
import cn.jussi.mvcproject.service.Userservice;
import cn.jussi.mvcproject.utils.CookieUtils;

/**
 * Serlet注释要生效  metadata-complete="false" (值必须为false)
 */
@WebServlet(urlPatterns= {"*.udo"})
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	Userservice userService = FactoryService.getUserService();
	OnlineService onlineService = FactoryService.getOnlineService();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		//System.out.println(req.getServletPath());
		String mn = req.getServletPath();
		mn = mn.substring(1, mn.length()-4);
		//System.out.println(mn);
		try {
			Method method = this.getClass().getDeclaredMethod(mn, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	
	/**
	 * 实现用户的注册
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User user = new User();
		user.setUsername(req.getParameter("username"));
		user.setPassword(req.getParameter("password"));
		user.setPhoneNum(req.getParameter("phoneNum"));
		user.setAddress(req.getParameter("address"));
		user.setRegDate(new Date());	
		int rows = userService.save(user);
		if(rows>0) {
			//跳转
			resp.sendRedirect(req.getContextPath()+"/main.jsp");
		}else {
			//throw new RuntimeException("注册失败！");
			resp.sendRedirect(req.getContextPath()+"/error.jsp");
		}
	}
	
	/**
	 * 实现首页的模糊查询
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String address = req.getParameter("address");
		String phoneNum = req.getParameter("phoneNum");
		username = username.replaceAll("[`~!@#$^&*()+|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;-|{}【】‘；：“”·。，、？]", "");
		address = address.replaceAll("[`~!@#$^&*()+|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;-|{}【】‘；：“”·。，、？]", "");
		phoneNum = phoneNum.replaceAll("[`~!@#$^&*()+|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;-|{}【】‘；：“”·。，、？]", "");
		List<User> list = userService.query(username, address, phoneNum);
		//System.out.println(list);
		//把结果集放到req的属性空间
		req.setAttribute("userList", list);
		//把整个req和resp注入到jsp界面
		req.getRequestDispatcher("/main.jsp").forward(req, resp);
	}
	
	/**
	 * 删除用户
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id"));
		int rows = userService.deleteUserById(id);
		if(rows>0) {
			resp.sendRedirect(req.getContextPath()+"/main.jsp");
		}else {
			resp.sendRedirect(req.getContextPath()+"/error.jsp");
		}
	}
	
	/**
	 * 查询要修改的用户
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id"));
		User user = userService.get(id);
		req.setAttribute("user", user);
		req.getRequestDispatcher("/update.jsp").forward(req, resp);
	}
	
	/**
	 * 修改要修改的用户
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private void updatedo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id"));
		User user = userService.get(id);
		String yUsername = user.getUsername();
		String xUsername = req.getParameter("username");
		int count = userService.getCountByName(xUsername);
		if(!xUsername.equals(yUsername) && count>0) {
			req.setAttribute("note", xUsername+",这个名字已被使用！");
			req.getRequestDispatcher("/update.udo?id="+id).forward(req, resp);
			return;
		}
		user.setUsername(xUsername);
		user.setPassword(req.getParameter("password"));
		user.setPhoneNum(req.getParameter("phoneNum"));
		user.setAddress(req.getParameter("address"));
		int rows = userService.updateUserById(user);
		if(rows>0) {
			resp.sendRedirect(req.getContextPath()+"/main.jsp");
		}else {
			resp.sendRedirect(req.getContextPath()+"/error.jsp");
		}
	}
	
	/**
	 * 用户登入方法
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String expiredays = req.getParameter("expiredays");
		Cookie[] cookies = req.getCookies();
		boolean login = false;	//是否登入的标志
		String account = null;	//登入账号
		String ssid = null;		//通过cookie拿到的一个判断用户该不该成功登入的标志
		if(cookies!=null && cookies.length>0) {
			for(Cookie cookie : cookies) {
				if(cookie.getName().equals("userKey")) {
					account = cookie.getValue();
				}
				if(cookie.getName().equals("ssid")) {
					ssid = cookie.getValue();
				}
			}
		}
		if(account != null && ssid != null) {
			login = ssid.equals(CookieUtils.md5Encrypt(username));
		}
		//System.out.println(login);
		if(!login) {	//用户还没登入
			//通过访问数据库，判断 用户名 和 密码 是否正确(正确返回一个User对象，不对返回null)
			User user = userService.login(username, password); 
			if(user != null) { //用户名 和 密码 正确,登入成功
				expiredays = expiredays==null ? "" : expiredays;
				switch (expiredays) {
				case "7":
					//创建一个cookie对象，设置cookie对象的时效时间为7天
					CookieUtils.createCookie(username, req, resp, 7*24*60*60);
					break;
				case "30":
					//创建一个cookie对象，设置cookie对象的时效时间为30天
					CookieUtils.createCookie(username, req, resp, 30*24*60*60);
					break;
				case "max":
					//创建一个cookie对象，设置cookie对象的时效时间为永远
					CookieUtils.createCookie(username, req, resp, Integer.MAX_VALUE);
					break;
				default:
					//创建一个cookie对象，设置cookie对象的时效时间为-1，浏览器一关闭就失效
					CookieUtils.createCookie(username, req, resp, -1);
					break;
				}
				//是否登入过的标志
				req.getSession().setAttribute("user", user.getUsername());
				//把在线状态online表里的username从 游客 改为 真正的 username
				HttpSession session = req.getSession();
				Online ol = onlineService.getOnlineBySsid(session.getId());
				if(ol != null) {
					ol.setUsername(username);
					onlineService.updateOnline(ol);
				}
				//登入成功的跳转页面
				resp.sendRedirect(req.getContextPath()+"/main.jsp");
			} else {
				req.setAttribute("note", "用户名或密码错误！");
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
			}
		} else {
			//是否登入过的标志
			req.getSession().setAttribute("user", username);
			//把在线状态online表里的username从 游客 改为 真正的 username
			HttpSession session = req.getSession();
			Online ol = onlineService.getOnlineBySsid(session.getId());
			if(ol != null) {
				ol.setUsername(username);
				onlineService.updateOnline(ol);
			}
			//登入成功的跳转页面
			resp.sendRedirect(req.getContextPath()+"/main.jsp");
		}	
	}
	
	@SuppressWarnings("unused")
	private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//记录登入状态的cookie删除
		Cookie[] cookies =  req.getCookies();
		if(cookies != null && cookies.length>0) {
			for(Cookie cookie: cookies) {
				if(cookie.getName().equals("userKey")) {
					cookie.setMaxAge(0);
					resp.addCookie(cookie);	//设置回客户端
				}
				if(cookie.getName().equals("ssid")) {
					cookie.setMaxAge(0);
					resp.addCookie(cookie);	//设置回客户端
				}
			}
		}
		//记录登入状态的session删除
		HttpSession session = req.getSession();
		if(session != null) {
			session.removeAttribute("user");
		}
		//退出登入以后，跳转到login.jsp
		resp.sendRedirect(req.getContextPath()+"/login.jsp");
	}
	
	/**
	 * 显示所有在线用户的信息
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	public void online(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Online> list = onlineService.getAllOnline();
		req.setAttribute("online", list);
		req.getRequestDispatcher("/online.jsp").forward(req, resp);
	}
}
